import React, { useEffect, useState } from 'react';
import { Card, Form, Input, Button, message, InputNumber, TreeSelect } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';
import { createStyles } from 'antd-style';
import { positionDetail, positionUpdate } from '@/services/system/postmanagement';
import CustomPageContainer from '@/components/CustomPageContainer';
import { deptpage } from '@/services/system/departmentmanage';
import { useModel } from '@umijs/max';

const useStyles = createStyles(({ token }) => ({
  container: {
    padding: '24px',
    background: '#f5f5f5',
    minHeight: 'calc(100vh - 48px)',
  },
  card: {
    borderRadius: '8px',
    boxShadow: '0 2px 8px rgba(0, 0, 0, 0.15)',
  },
  formContainer: {
    maxWidth: '800px',
    margin: '0 auto',
    padding: '24px',
  },
  title: {
    fontSize: '16px',
    fontWeight: 'bold',
    color: '#1890ff',
    borderBottom: '2px solid #1890ff',
    paddingBottom: '8px',
    marginBottom: '24px',
  },
  formItem: {
    marginBottom: '16px',
    '& .ant-form-item-label': {
      fontWeight: 500,
      color: '#333',
    },
    '& .ant-input': {
      borderRadius: '4px',
      '&:focus': {
        borderColor: '#1890ff',
        boxShadow: '0 0 0 2px rgba(24, 144, 255, 0.2)',
      },
    },
  },
  buttonGroup: {
    display: 'flex',
    justifyContent: 'center',
    gap: '16px',
    marginTop: '32px',
  },
  button: {
    width: '120px',
    height: '36px',
    borderRadius: '4px',
    fontSize: '14px',
  },
}));

interface DeptTreeItem {
  id: number;
  departmentId: string;
  deptName: string;
  fullName: string;
  deptCategory: number;
  parementId: string | null;
  ancestors: string;
  children?: DeptTreeItem[];
  isDeleted: number;
  remark: string;
  sort: number;
}

interface TreeDataNode {
  title: string;
  value: number | string;
  key: number | string;
  children?: TreeDataNode[];
}

const PostManagementEdit: React.FC = () => {
  const { styles } = useStyles();
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const location = useLocation();
  const { record } = location.state || {};
  const [deptTreeData, setDeptTreeData] = useState<DeptTreeItem[]>([]);
  const { institutionId, institutionRoleId } = useModel('auth');
  const [detailData, setDetailData] = useState<any>(null);

  const convertToTreeData = (deptList: DeptTreeItem[]): TreeDataNode[] => {
    return deptList.map(dept => ({
      title: dept.deptName,
      value: dept.departmentId,
      key: dept.departmentId,
      children: dept.children ? convertToTreeData(dept.children) : undefined
    }));
  };

  const fetchDeptTree = async () => {
    try {
      const response = await deptpage({
        institutionId: institutionId,
        institutionRoleId: institutionRoleId,
      });
      if (response.code === 200 && response.success) {
        setDeptTreeData(response.data);
      } else {
        message.error('获取部门列表失败');
      }
    } catch (error) {
      console.error('获取部门列表失败:', error);
      message.error('获取部门列表失败');
    }
  };

  const fetchDetailData = async () => {
    if (!record?.id) return;

    try {
      const detailRes = await positionDetail({
        positionId: record.positionId,
        institutionId: institutionId,
        institutionRoleId: institutionRoleId,
      });
      if (detailRes.code === 200) {
        setDetailData(detailRes.data);
      } else {
        message.error('获取岗位详情失败');
        navigate('/system/postmanagement');
      }
    } catch (error) {
      console.error('获取数据失败:', error);
      message.error('获取数据失败');
      navigate('/system/postmanagement');
    }
  };

  // 获取部门树数据
  useEffect(() => {
    fetchDeptTree();
  }, []);

  // 获取详情数据
  useEffect(() => {
    fetchDetailData();
  }, [record?.id]);

  // 处理数据回显
  useEffect(() => {
    if (detailData && deptTreeData.length > 0) {
      const findDeptId = (deptList: DeptTreeItem[], targetId: string): string => {
        for (const dept of deptList) {
          if (dept.departmentId === targetId) {
            return dept.departmentId;
          }
          if (dept.children) {
            const found = findDeptId(dept.children, targetId);
            if (found) return found;
          }
        }
        return '';
      };

      form.setFieldsValue({
        positionName: detailData.positionName,
        sort: detailData.sort,
        description: detailData.description,
        parementId: findDeptId(deptTreeData, detailData.departmentId) || '',
      });
    }
  }, [detailData, deptTreeData]);

  const onFinish = async (values: any) => {
    console.log('values:', values);
    try {
      const params = {
        ...values,
        institutionId: institutionId,
        institutionRoleId: institutionRoleId,
        departmentId: values.parementId,
        positionId: record.positionId,
      };
      console.log('params:', params);

      const response = await positionUpdate(params);
      if (response.code === 200) {
        message.success('修改岗位成功');
        navigate('/system/postmanagement');
      } else {
        message.error(response.msg || '修改岗位失败');
      }
    } catch (error) {
      console.error('提交失败:', error);
      message.error('修改岗位失败');
    }
  };

  return (
    <CustomPageContainer>
      <div className={styles.container}>
        <Card className={styles.card}>
          <div className={styles.formContainer}>
            <div className={styles.title}>岗位修改</div>
            <Form
              form={form}
              layout="vertical"
              onFinish={onFinish}
            >
              <Form.Item
                label="岗位名称："
                name="positionName"
                className={styles.formItem}
                rules={[{ required: true, message: '请输入岗位名称' }]}
              >
                <Input placeholder="审核员" />
              </Form.Item>

              <Form.Item
                label="岗位排序："
                name="sort"
                className={styles.formItem}
                rules={[{ required: true, message: '请输入岗位排序' }]}
                initialValue={1}
              >
                <InputNumber min={1} style={{ width: '100%' }} placeholder="1" />
              </Form.Item>

              <Form.Item
                label="上级部门"
                name="parementId"
                className={styles.formItem}
                rules={[{
                  required: true,
                  message: '请选择上级部门',
                  validator: (_, value) => {
                    if (value === '' || value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('请选择上级部门'));
                  }
                }]}
              >
                <TreeSelect
                  placeholder="请选择上级部门"
                  allowClear
                  showSearch
                  treeDefaultExpandAll
                  style={{ width: '100%' }}
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  treeData={[

                    ...convertToTreeData(deptTreeData)
                  ]}
                  treeNodeFilterProp="title"
                />
              </Form.Item>

              <Form.Item
                label="岗位备注："
                name="description"
                className={styles.formItem}
              >
                <Input.TextArea
                  rows={4}
                  placeholder="该岗位负责部门审核工作。"
                />
              </Form.Item>

              <div className={styles.buttonGroup}>
                <Button
                  className={styles.button}
                  onClick={() => navigate('/system/postmanagement')}
                >
                  返回
                </Button>
                <Button
                  type="primary"
                  htmlType="submit"
                  className={styles.button}
                >
                  确定
                </Button>
              </div>
            </Form>
          </div>
        </Card>
      </div>
    </CustomPageContainer>
  );
};

export default PostManagementEdit;

